package cc.lj.internal.payment.domain.pay.service.impl;

import cc.lj.internal.core.exception.ServiceException;
import cc.lj.internal.payment.domain.pay.repository.IPayFormListRepository;
import cc.lj.internal.payment.domain.pay.service.IPayFormListDomainService;
import cc.lj.internal.payment.domain.pay.vo.PayformListDO;
import cc.lj.internal.payment.domain.pay.vo.convert.PayFormListPOConvertDO;
import cc.lj.internal.payment.infrastructure.exception.PaymentExceptionEnum;
import cc.lj.internal.payment.infrastructure.po.PayformListPO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 现金+购物券支付方式表领域服务service实现类
 * @author liangxifeng
 * @date 2021-01-17
 */
@Service("payFormListDomainServiceImpl")
@Slf4j
public class PayFormListDomainServiceImpl implements IPayFormListDomainService {
    @Resource(name = "payFromListRepository")
    private IPayFormListRepository repository;

    @Override
    public Integer insert(PayformListDO payformListDO) {
        PayformListPO PayformListPO = PayFormListPOConvertDO.INSTANCE.convert(payformListDO);
        return repository.insert(PayformListPO);
    }

    @Override
    public Integer updateById(PayformListDO payformListDO) {
        PayformListPO payformListPO = PayFormListPOConvertDO.INSTANCE.convert(payformListDO);
        return repository.updateById(payformListPO);
    }

    /**
     * 标准批量获取数据的方法
     * @param payformListDO
     * @return list
     */
    public List<PayformListDO> getList(PayformListDO payformListDO)
    {
        PayformListPO payformListPO = PayFormListPOConvertDO.INSTANCE.convert(payformListDO);
        List<PayformListPO> list = repository.getList(payformListPO);
        List<PayformListDO> newList = new ArrayList<>();
        for(PayformListPO item : list)
        {
            newList.add(PayFormListPOConvertDO.INSTANCE.convert(item));
        }
        return newList;
    }

    @Override
    public PayformListPO getByConsumeId(Integer consumeId) {
        PayformListPO payformListPO = new PayformListPO();
        payformListPO.setPayformConsumeId(consumeId);
        List<PayformListPO>  listPO = repository.getList(payformListPO);
        if(listPO.size() == 1) {
            return listPO.get(0);
        }else {
            throw new ServiceException(PaymentExceptionEnum.GET_PAYFORM_LIST_BY_CONSUMERID_FAILED);
        }
    }

    @Override
    public Integer updateByConsumeId(PayformListDO payformListDO) {
        PayformListPO payformListPO = PayFormListPOConvertDO.INSTANCE.convert(payformListDO);
        //先通过consumerId查询
        PayformListPO resPO = getByConsumeId(payformListDO.getPayformConsumeId());
        //获取主键后，通过主键修改
        payformListPO.setPayformId(resPO.getPayformId()); //主键
        payformListPO.setPayformConsumeId(null); //不修改consumeId
        //通过主键修改
        return repository.updateById(payformListPO);
    }
}
